package com.qm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qm.pojo.Order;
import com.qm.pojo.OrderItem;
import com.qm.pojo.OrderShipping;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.qm.mapper.OrderItemMapper;
import com.qm.mapper.OrderMapper;
import com.qm.mapper.OrderShippingMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements DubboOrderService {
	
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderShippingMapper orderShippingMapper;
	@Autowired
	private OrderItemMapper orderItemMapper;


	@Override
	@Transactional//控制事务
	public String saveOrder(Order order) {
		String orderId = ""+order.getUserId() + System.currentTimeMillis();
		Date date = new Date();
		//1.订单入库
		order.setOrderId(orderId)
			 .setStatus(1)//未付款
			 .setCreated(date).setUpdated(date);
		orderMapper.insert(order);
		System.out.println("订单入库成功！！！");
		//2.订单物流入库
		OrderShipping orderShipping = order.getOrderShipping();
		orderShipping.setOrderId(orderId)
					 .setCreated(date)
					 .setUpdated(date);
		orderShippingMapper.insert(orderShipping);
		System.out.println("订单物流入库成功！！！");
		//3.商品信息入库（一对多）
		List<OrderItem> orderItems = order.getOrderItems();
		for (OrderItem orderItem : orderItems ) {
			orderItem.setOrderId(orderId)
					 .setCreated(date)
					 .setUpdated(date);
			orderItemMapper.insert(orderItem);
		}
		System.out.println("订单商品入库成功！！！");
		return orderId;
	}

	@Override
	public Order findOrderById(String orderId) {
		Order order = orderMapper.selectById(orderId);
		OrderShipping orderShipping = orderShippingMapper.selectById(orderId);
		QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("order_id", orderId);
		List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);
		return order.setOrderShipping(orderShipping)
					.setOrderItems(orderItems);
	}
}
